//
//  OPHelperWeatherController.m
//  OnePiece
//
//  Created by wsy on 15/10/30.
//  Copyright © 2015年 wsy. All rights reserved.
//

#import "OPHelperWeatherController.h"
#import "OPWeatherView.h"
#import <CoreLocation/CoreLocation.h>
@interface OPHelperWeatherController ()<CLLocationManagerDelegate,UITextFieldDelegate>
@property (nonatomic, strong) OPWeatherView *weatherView;
@property (nonatomic, strong) UIView *blackView;
@property (nonatomic, strong) UITextField *placeTF;
@property (nonatomic, strong) UIView *orangeView;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) UIButton *ensurePlace;
@property (nonatomic, strong) UIButton *ensure;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *geocoder;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, copy) NSString *city;
@end

@implementation OPHelperWeatherController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _weatherView = [[OPWeatherView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.view addSubview:_weatherView];
    _weatherView.mainScr.backgroundColor = [UIColor colorWithRed:0.945 green:0.458 blue:0.299 alpha:1.000];
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backButton.frame = CGRectMake(20, 30, 30, 30);
    [backButton addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    [backButton setImage:[UIImage imageNamed:@"iconfont-weibiaoti1"] forState:(UIControlStateNormal)];
    [self.view addSubview:backButton];
    [_weatherView.changeButton addTarget:self action:@selector(changePlace) forControlEvents:(UIControlEventTouchUpInside)];
    _blackView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-42, 37, 1, 1)];
    _blackView.backgroundColor = [UIColor colorWithRed:0.945 green:0.458 blue:0.299 alpha:1.000];
    [self configureSearchView];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user valueForKey:@"city"] == nil) {
        _city = @"shanghai";
    }else{
        _city = [user valueForKey:@"city"];
    }
    
    NSString *cityurl = [_city stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *httpUrl = @"http://apis.baidu.com/heweather/weather/free";
    NSString *httpArg = [NSString stringWithFormat:@"city=%@",cityurl];
    [self request: httpUrl withHttpArg: httpArg];
    
    if (![[[NSUserDefaults standardUserDefaults]valueForKey:@"weatherFirstStart"] isEqualToString:@"YES"]) {
        [self configureGuideView];
    }else{
        [_backgroundView removeFromSuperview];
    }
}


// 开始定位的方法
- (void)startLocation{
    _locationManager=[[CLLocationManager alloc]init];
    _locationManager.delegate = self;
    [_locationManager requestAlwaysAuthorization];
    [_locationManager startUpdatingLocation];
    
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"查询天气可能用到定位系统，要不要开启呢？");
        return;
    }
    
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [_locationManager requestWhenInUseAuthorization];
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
        //设置代理
        _locationManager.delegate=self;
        //设置定位精度(这里是个枚举值)
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        CLLocationDistance distance=10.0;//十米定位一次
        _locationManager.distanceFilter=distance;
        //启动跟踪定位
        [_locationManager startUpdatingLocation];
    }
    self.geocoder = [[CLGeocoder alloc]init];
}
#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一个位置
    _coordinate=location.coordinate;//位置坐标
//    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",_coordinate.longitude,_coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
    
   
}
#pragma mark - 根据坐标取得地名
- (void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude
{
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks firstObject];
//        NSLog(@"详细信息:%@", placemark.addressDictionary);
        _placeTF.text = placemark.addressDictionary[@"City"];
        [[NSUserDefaults standardUserDefaults]setValue:_placeTF.text forKey:@"city"];
        NSLog(@"%@",_placeTF.text);
    }];
}
// 网络请求
-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"d3b385f6717b59a2c7eccda12a00367a" forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
       if (error) {
           NSLog(@"Httperror: %@", error.localizedDescription);
       } else {
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
           if ([dic[@"HeWeather data service 3.0"][0][@"status"] isEqualToString:@"ok"]) {
               NSArray *arr = dic[@"HeWeather data service 3.0"][0][@"daily_forecast"];
               [_weatherView setNext:arr];
               NSDictionary *basicDic = dic[@"HeWeather data service 3.0"][0];
               OPWeatherBaseModel *baseModel = [[OPWeatherBaseModel alloc]init];
               [baseModel setValuesForKeysWithDictionary:basicDic];
               [_weatherView setBaseModel:baseModel];
               [[NSUserDefaults standardUserDefaults]setValue:baseModel.basic[@"city"] forKey:@"city"];
               NSDictionary *sugDic = dic[@"HeWeather data service 3.0"][0][@"suggestion"];
               OPWeatherSuggestionModel *sugModel = [[OPWeatherSuggestionModel alloc]init];
               [sugModel setValuesForKeysWithDictionary:sugDic];
               [_weatherView setSuggestionModel:sugModel];
           }else{
               UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请求错误" preferredStyle:UIAlertControllerStyleAlert];
               UIAlertAction *ensure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
               [alert addAction:ensure];
               [self presentViewController:alert animated:YES completion:nil];
           }
           
       }
   }];
}

// 配置查询界面
- (void)configureSearchView
{
    _orangeView = [[UIView alloc]initWithFrame:CGRectZero];
    _orangeView.backgroundColor = [UIColor colorWithRed:0.945 green:0.458 blue:0.299 alpha:1.000];
    [_blackView addSubview:_orangeView];
    _placeTF = [[UITextField alloc]initWithFrame:CGRectZero];
    _placeTF.borderStyle = UITextBorderStyleNone;
    _placeTF.delegate = self;
    _placeTF.placeholder = @"请输入目标城市";
    [_orangeView addSubview:_placeTF];
    _line = [[UIView alloc]initWithFrame:CGRectZero];
    _line.backgroundColor = [UIColor whiteColor];
    [_orangeView addSubview:_line];
    _ensurePlace = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _ensurePlace.frame = CGRectZero;
    _ensurePlace.layer.borderWidth = 2;
    _ensurePlace.layer.cornerRadius = 5;
    _ensurePlace.layer.borderColor = [[UIColor whiteColor] CGColor];
    [_ensurePlace setTitle:@"定位当前城市" forState:(UIControlStateNormal)];
    [_ensurePlace addTarget:self action:@selector(ensurePlace:) forControlEvents:(UIControlEventTouchUpInside)];
    _ensurePlace.titleLabel.font = [UIFont systemFontOfSize:1];
    [_ensurePlace setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [_orangeView addSubview:_ensurePlace];
    _ensure = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _ensure.frame = CGRectZero;
    _ensure.layer.borderWidth = 2;
    _ensure.layer.cornerRadius = 5;
    _ensure.layer.borderColor = [[UIColor whiteColor] CGColor];
    [_ensure setTitle:@"确认搜索" forState:(UIControlStateNormal)];
    [_ensure addTarget:self action:@selector(configureWeather:) forControlEvents:(UIControlEventTouchUpInside)];
    _ensure.titleLabel.font = [UIFont systemFontOfSize:1];
    [_ensure setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [_orangeView addSubview:_ensure];
    
}

// 查询界面弹出
- (void)changePlace
{
    _blackView.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.500];
    [UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        _blackView.frame = [[UIScreen mainScreen] bounds];
        _orangeView.frame = CGRectMake(50, 100, SCREEN_WIDTH-100, 200);
        _placeTF.frame = CGRectMake(30, 40, SCREEN_WIDTH-160, 40);
        _line.frame = CGRectMake(30, 80, SCREEN_WIDTH-160, 2);
        _ensurePlace.frame = CGRectMake(30, 100, SCREEN_WIDTH-160, 30);
        _ensure.frame = CGRectMake(30, 140, SCREEN_WIDTH-160, 30);
        
    } completion:nil];
    [self performSelector:@selector(changeFont) withObject:nil afterDelay:2]; //确保字体在view放大之后再放大
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(remove)];
    [_blackView addGestureRecognizer:tap];
    [self.view addSubview:_blackView];
}
// 弹出查询界面后改变字体大小，防止弹出瞬间变大
- (void)changeFont
{
    _ensurePlace.titleLabel.font = [UIFont systemFontOfSize:20];
    _ensure.titleLabel.font = [UIFont systemFontOfSize:20];
}
// 将查询界面收回
- (void)remove{
    _ensurePlace.titleLabel.font = [UIFont systemFontOfSize:1];
    _ensure.titleLabel.font = [UIFont systemFontOfSize:1];
    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        _blackView.frame = CGRectMake(SCREEN_WIDTH-42, 37, 1, 1);
        _orangeView.frame = CGRectZero;
        _placeTF.frame = CGRectZero;
        _line.frame = CGRectZero;
        _ensurePlace.frame = CGRectZero;
        _ensure.frame = CGRectZero;
        _blackView.backgroundColor = [UIColor colorWithRed:0.945 green:0.458 blue:0.299 alpha:1.000];
    } completion:nil];
}

// 定位当前城市
- (void)ensurePlace:(UIButton *)sender{
    [self startLocation];
    [self getAddressByLatitude:_coordinate.latitude longitude:_coordinate.longitude];
}

// 确认查询
- (void)configureWeather:(UIButton *)sender{
    if ([_placeTF.text containsString:@"市"]) {
        _city = [_placeTF.text stringByReplacingOccurrencesOfString:@"市" withString:@""];
    }else{
        _city = _placeTF.text;
    }
    
    [[NSUserDefaults standardUserDefaults]setValue:_placeTF.text forKey:@"city"];
    NSString *cityurl = [_city stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *httpUrl = @"http://apis.baidu.com/heweather/weather/free";
    NSString *httpArg = [NSString stringWithFormat:@"city=%@",cityurl];
    [self request: httpUrl withHttpArg: httpArg];
    [self remove];
    [_placeTF resignFirstResponder];
}

- (void)configureGuideView{
    _backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*2)];
    _backgroundView.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.500];
    [_weatherView.mainScr addSubview:_backgroundView];
    UILabel *suggestion = [[UILabel alloc]initWithFrame:CGRectMake(50, SCREEN_HEIGHT/2+180, 200, 30)];
    suggestion.text = @"便签式旅行建议(*^__^*)";
    suggestion.textColor = [UIColor whiteColor];
    [_backgroundView addSubview:suggestion];
    UIImageView *tosug = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"iconfont-iconfont"]];
    tosug.frame = CGRectMake(100, SCREEN_HEIGHT/2+80, 60, 60);
    [_backgroundView addSubview:tosug];
    UILabel *shanghua = [[UILabel alloc]initWithFrame:CGRectMake(50, SCREEN_HEIGHT-50, 180, 30)];
    shanghua.text = @"上滑显示天气详情☀️";
    shanghua.textColor = [UIColor whiteColor];
    [_backgroundView addSubview:shanghua];
    UIImageView *shanghuaimg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"iconfont-zhongchouh5erqishanghua"]];
    shanghuaimg.frame = CGRectMake(240, SCREEN_HEIGHT-60, 40, 40);
    [_backgroundView addSubview:shanghuaimg];
    UILabel *ditu = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-190, SCREEN_HEIGHT+100, 190, 60)];
    ditu.numberOfLines = 0;
    ditu.text = @"点击定位标识进行定位和城市搜索";
    ditu.textColor = [UIColor whiteColor];
    [_backgroundView addSubview:ditu];
    UIImageView *toditu = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"iconfont-iconfont"]];
    toditu.frame = CGRectMake(SCREEN_WIDTH-80, SCREEN_HEIGHT+50, 40, 40);
    [_backgroundView addSubview:toditu];
    UIButton *getit = [UIButton buttonWithType:(UIButtonTypeCustom)];
    getit.frame = CGRectMake(SCREEN_WIDTH/2-50, SCREEN_HEIGHT+SCREEN_HEIGHT/2, 100, 30);
    [getit setTitle:@"我知道了" forState:(UIControlStateNormal)];
    getit.layer.borderColor = [[UIColor whiteColor]CGColor];
    getit.layer.cornerRadius = 5;
    getit.layer.borderWidth = 1.3;
    [getit setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [getit addTarget:self action:@selector(getit) forControlEvents:(UIControlEventTouchUpInside)];
    [_backgroundView addSubview:getit];
    
}

- (void)getit
{
    [_backgroundView removeFromSuperview];
    [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"weatherFirstStart"];
}



// 返回按钮
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
// 键盘回收
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_placeTF resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
